using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.IO;

namespace DocumentCreationSystem.ViewModels
{
    public partial class MainWindowViewModel : ObservableObject
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<MainWindowViewModel> _logger;
        private readonly IAIService _aiService;
        private readonly IProjectService _projectService;
        private readonly IDocumentService _documentService;
        private readonly IVectorService _vectorService;
        private readonly INovelCreationService _novelCreationService;

        [ObservableProperty]
        private string _statusMessage = "系统就绪";

        [ObservableProperty]
        private bool _isSystemReady = true;

        [ObservableProperty]
        private string _currentProjectName = "未打开项目";

        [ObservableProperty]
        private int _wordCount = 0;

        [ObservableProperty]
        private int _currentLine = 1;

        [ObservableProperty]
        private int _currentColumn = 1;

        [ObservableProperty]
        private double _temperature = 0.7;

        [ObservableProperty]
        private int _maxTokens = 2000;

        [ObservableProperty]
        private string _currentChapter = "第1章";

        [ObservableProperty]
        private int _chapterProgress = 0;

        [ObservableProperty]
        private int _chapterTarget = 6500;

        [ObservableProperty]
        private ObservableCollection<AIModel> _availableModels = new();

        [ObservableProperty]
        private AIModel? _selectedModel;

        [ObservableProperty]
        private ObservableCollection<ProjectTreeItem> _projectItems = new();

        [ObservableProperty]
        private ProjectTreeItem? _selectedProjectItem;

        [ObservableProperty]
        private string _documentContent = string.Empty;

        [ObservableProperty]
        private string? _currentDocumentPath;

        [ObservableProperty]
        private bool _isProcessing = false;

        public MainWindowViewModel(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
            _logger = serviceProvider.GetRequiredService<ILogger<MainWindowViewModel>>();
            _aiService = serviceProvider.GetRequiredService<IAIService>();
            _projectService = serviceProvider.GetRequiredService<IProjectService>();
            _documentService = serviceProvider.GetRequiredService<IDocumentService>();
            _vectorService = serviceProvider.GetRequiredService<IVectorService>();
            _novelCreationService = serviceProvider.GetRequiredService<INovelCreationService>();

            InitializeAsync();
        }

        private async void InitializeAsync()
        {
            try
            {
                await LoadAIModelsAsync();
                await LoadProjectsAsync();
                _logger.LogInformation("MainWindowViewModel 初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化 MainWindowViewModel 时发生错误");
                StatusMessage = $"初始化失败: {ex.Message}";
                IsSystemReady = false;
            }
        }

        private async Task LoadAIModelsAsync()
        {
            try
            {
                List<AIModel> models;

                // 如果AIService是AIServiceManager，优先获取当前提供者的模型
                if (_aiService is AIServiceManager aiServiceManager)
                {
                    models = await aiServiceManager.GetCurrentProviderModelsAsync();
                    var providerName = aiServiceManager.GetCurrentProviderName();
                    _logger.LogInformation($"加载当前提供者 ({providerName}) 的模型");
                }
                else
                {
                    // 否则获取所有模型
                    models = await _aiService.GetAvailableModelsAsync();
                }

                AvailableModels.Clear();
                foreach (var model in models)
                {
                    AvailableModels.Add(model);
                }

                // 获取当前已配置的模型，而不是强制选择第一个
                var currentModel = _aiService.GetCurrentModel();
                if (currentModel != null)
                {
                    // 在可用模型列表中找到当前模型
                    var selectedModel = AvailableModels.FirstOrDefault(m => m.Id == currentModel.Id);
                    if (selectedModel != null)
                    {
                        SelectedModel = selectedModel;
                        _logger.LogInformation($"使用已配置的当前模型: {selectedModel.Name} ({selectedModel.Provider})");
                    }
                    else
                    {
                        // 如果当前模型不在可用列表中，选择第一个可用模型
                        if (AvailableModels.Any())
                        {
                            SelectedModel = AvailableModels.First();
                            await _aiService.SetCurrentModelAsync(SelectedModel.Id);
                            _logger.LogInformation($"当前模型不可用，切换到: {SelectedModel.Name} ({SelectedModel.Provider})");
                        }
                    }
                }
                else if (AvailableModels.Any())
                {
                    // 如果没有当前模型，选择第一个可用模型
                    SelectedModel = AvailableModels.First();
                    await _aiService.SetCurrentModelAsync(SelectedModel.Id);
                    _logger.LogInformation($"设置默认模型: {SelectedModel.Name} ({SelectedModel.Provider})");
                }

                _logger.LogInformation($"加载了 {models.Count} 个AI模型");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载AI模型时发生错误");
                StatusMessage = "AI模型加载失败";
                IsSystemReady = false;
            }
        }

        /// <summary>
        /// 刷新AI模型列表（公共方法，供外部调用）
        /// </summary>
        public async Task RefreshAIModelsAsync()
        {
            await LoadAIModelsAsync();
        }

        private async Task LoadProjectsAsync()
        {
            try
            {
                var projects = await _projectService.GetAllProjectsAsync();
                ProjectItems.Clear();

                foreach (var project in projects)
                {
                    var projectItem = new ProjectTreeItem
                    {
                        Name = project.Name,
                        Type = ProjectTreeItemType.Project,
                        ProjectId = project.Id,
                        FilePath = project.RootPath, // 设置项目文件夹路径
                        Children = new ObservableCollection<ProjectTreeItem>()
                    };

                    // 检查项目路径是否有效，如果无效则跳过该项目
                    if (!projectItem.HasValidPath)
                    {
                        _logger.LogWarning($"项目 '{project.Name}' 的路径无效，已跳过: {project.RootPath}");
                        continue;
                    }

                    // 加载项目下的文档
                    var documents = await _documentService.GetProjectDocumentsAsync(project.Id);
                    foreach (var doc in documents)
                    {
                        var docItem = new ProjectTreeItem
                        {
                            Name = doc.FileName,
                            Type = ProjectTreeItemType.Document,
                            DocumentId = doc.Id,
                            ProjectId = project.Id
                        };
                        projectItem.Children.Add(docItem);
                    }

                    ProjectItems.Add(projectItem);
                }

                _logger.LogInformation($"加载了 {projects.Count} 个项目");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载项目时发生错误");
            }
        }

        /// <summary>
        /// 公共的刷新项目方法，供外部调用
        /// </summary>
        public async Task RefreshProjectsAsync()
        {
            await LoadProjectsAsync();
        }

        [RelayCommand]
        private async Task NewProject()
        {
            try
            {
                IsProcessing = true;
                StatusMessage = "正在创建新项目...";

                // 显示新建项目对话框
                var dialog = new DocumentCreationSystem.Views.NewProjectDialog();
                if (dialog.ShowDialog() == true && dialog.IsConfirmed)
                {
                    var project = await _projectService.CreateProjectAsync(
                        dialog.ProjectName,
                        dialog.ProjectType,
                        dialog.ProjectPath,
                        dialog.ProjectDescription);

                    // 如果是小说项目，创建小说项目记录
                    if (dialog.ProjectType == "Novel")
                    {
                        await _novelCreationService.CreateNovelProjectAsync(
                            project.Id,
                            dialog.ProjectName,
                            dialog.CreativeDirection,
                            dialog.TargetChapterCount,
                            dialog.TargetWordsPerChapter);
                    }

                    await LoadProjectsAsync();
                    CurrentProjectName = project.Name;
                    StatusMessage = "项目创建成功";

                    _logger.LogInformation($"创建新项目: {dialog.ProjectName}");
                }
                else
                {
                    StatusMessage = "取消创建项目";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建项目时发生错误");
                StatusMessage = "项目创建失败";
            }
            finally
            {
                IsProcessing = false;
            }
        }

        [RelayCommand]
        private async Task OpenProject()
        {
            try
            {
                IsProcessing = true;
                StatusMessage = "正在打开项目...";

                // 弹出文件夹选择对话框
                var dialog = new Microsoft.Win32.OpenFolderDialog
                {
                    Title = "选择项目文件夹",
                    Multiselect = false
                };

                if (dialog.ShowDialog() == true)
                {
                    var selectedPath = dialog.FolderName;

                    // 检查是否是有效的项目文件夹
                    if (await IsValidProjectFolder(selectedPath))
                    {
                        // 尝试从数据库加载项目
                        var existingProject = await _projectService.GetProjectByPathAsync(selectedPath);

                        if (existingProject != null)
                        {
                            // 项目已存在，直接打开
                            await LoadSpecificProject(existingProject.Id);
                            CurrentProjectName = existingProject.Name;
                            StatusMessage = "项目打开成功";
                        }
                        else
                        {
                            // 项目不在数据库中，询问是否导入
                            var projectName = Path.GetFileName(selectedPath);
                            var result = System.Windows.MessageBox.Show(
                                $"文件夹 '{projectName}' 不是已知项目。是否要将其导入为新项目？",
                                "导入项目",
                                System.Windows.MessageBoxButton.YesNo,
                                System.Windows.MessageBoxImage.Question);

                            if (result == System.Windows.MessageBoxResult.Yes)
                            {
                                // 创建新项目记录
                                var project = await _projectService.CreateProjectAsync(
                                    projectName,
                                    "Normal",
                                    selectedPath,
                                    $"从文件夹导入的项目: {selectedPath}");

                                await LoadProjectsAsync();
                                CurrentProjectName = project.Name;
                                StatusMessage = "项目导入成功";
                            }
                            else
                            {
                                StatusMessage = "取消导入项目";
                            }
                        }
                    }
                    else
                    {
                        StatusMessage = "选择的文件夹不是有效的项目文件夹";
                    }
                }
                else
                {
                    StatusMessage = "取消打开项目";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开项目时发生错误");
                StatusMessage = "项目打开失败";
            }
            finally
            {
                IsProcessing = false;
            }
        }

        private Task<bool> IsValidProjectFolder(string folderPath)
        {
            try
            {
                // 检查文件夹是否存在
                if (!Directory.Exists(folderPath))
                    return Task.FromResult(false);

                // 检查是否包含项目文件或文档文件
                var files = Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly);
                var hasDocuments = files.Any(f =>
                {
                    var ext = Path.GetExtension(f).ToLower();
                    return ext == ".txt" || ext == ".md" || ext == ".docx" || ext == ".doc";
                });

                var result = hasDocuments || Directory.GetDirectories(folderPath).Length > 0;
                return Task.FromResult(result);
            }
            catch
            {
                return Task.FromResult(false);
            }
        }

        private async Task LoadSpecificProject(int projectId)
        {
            try
            {
                var project = await _projectService.GetProjectByIdAsync(projectId);
                if (project != null)
                {
                    // 更新项目树
                    await LoadProjectsAsync();

                    // 选择对应的项目
                    var projectItem = ProjectItems.FirstOrDefault(p => p.ProjectId == projectId);
                    if (projectItem != null)
                    {
                        SelectedProjectItem = projectItem;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"加载特定项目失败，项目ID: {projectId}");
                throw;
            }
        }

        [RelayCommand]
        private async Task SaveDocument()
        {
            try
            {
                IsProcessing = true;
                StatusMessage = "正在保存文档...";

                if (SelectedProjectItem?.DocumentId != null)
                {
                    await _documentService.SaveDocumentAsync(SelectedProjectItem.DocumentId.Value, DocumentContent);
                    StatusMessage = "文档保存成功";
                }
                else
                {
                    StatusMessage = "没有选中的文档";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存文档时发生错误");
                StatusMessage = "文档保存失败";
            }
            finally
            {
                IsProcessing = false;
            }
        }

        [RelayCommand]
        private async Task PolishText()
        {
            try
            {
                IsProcessing = true;
                StatusMessage = "正在润色文本...";

                if (!string.IsNullOrWhiteSpace(DocumentContent))
                {
                    var polishedText = await _aiService.PolishTextAsync(DocumentContent, "文学");
                    DocumentContent = polishedText;
                    StatusMessage = "文本润色完成";
                }
                else
                {
                    StatusMessage = "没有内容可润色";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "润色文本时发生错误");
                StatusMessage = "润色失败";
            }
            finally
            {
                IsProcessing = false;
            }
        }

        [RelayCommand]
        private async Task ExpandText()
        {
            try
            {
                IsProcessing = true;
                StatusMessage = "正在扩写内容...";

                if (!string.IsNullOrWhiteSpace(DocumentContent))
                {
                    var expandedText = await _aiService.ExpandTextAsync(DocumentContent, MaxTokens, "");
                    DocumentContent = expandedText;
                    StatusMessage = "内容扩写完成";
                }
                else
                {
                    StatusMessage = "没有内容可扩写";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "扩写内容时发生错误");
                StatusMessage = "扩写失败";
            }
            finally
            {
                IsProcessing = false;
            }
        }

        [RelayCommand]
        private async Task GenerateOutline()
        {
            try
            {
                IsProcessing = true;
                StatusMessage = "正在生成大纲...";

                var direction = "一个现代都市修仙小说，主角是一名普通的大学生";
                var outline = await _aiService.GenerateTextAsync($"请为以下小说创意生成详细大纲：{direction}");
                DocumentContent = outline;
                StatusMessage = "大纲生成完成";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成大纲时发生错误");
                StatusMessage = "大纲生成失败";
            }
            finally
            {
                IsProcessing = false;
            }
        }

        [RelayCommand]
        private async Task CreateChapter()
        {
            try
            {
                IsProcessing = true;
                StatusMessage = "正在创作章节...";

                var chapterOutline = "第一章：觉醒 - 主角在图书馆发现古籍，觉醒修仙资质";
                var chapterContent = await _aiService.GenerateTextAsync($"请根据以下章节大纲创作详细内容：{chapterOutline}");
                DocumentContent = chapterContent;
                StatusMessage = "章节创作完成";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创作章节时发生错误");
                StatusMessage = "章节创作失败";
            }
            finally
            {
                IsProcessing = false;
            }
        }

        [RelayCommand]
        private async Task CheckConsistency()
        {
            try
            {
                IsProcessing = true;
                StatusMessage = "正在检查一致性...";

                if (!string.IsNullOrWhiteSpace(DocumentContent))
                {
                    var previousContext = "林晨是一名大学生，性格内向";
                    var result = await _aiService.CheckConsistencyAsync(DocumentContent, previousContext);
                    StatusMessage = $"一致性检查完成: {(result.IsConsistent ? "通过" : "发现问题")}";
                }
                else
                {
                    StatusMessage = "没有内容可检查";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查一致性时发生错误");
                StatusMessage = "一致性检查失败";
            }
            finally
            {
                IsProcessing = false;
            }
        }

        partial void OnSelectedModelChanged(AIModel? value)
        {
            if (value != null)
            {
                _ = Task.Run(async () =>
                {
                    try
                    {
                        await _aiService.SetCurrentModelAsync(value.Id);
                        StatusMessage = $"已切换到模型: {value.Name}";
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"切换AI模型失败: {value.Id}");
                        StatusMessage = "模型切换失败";
                    }
                });
            }
        }

        partial void OnDocumentContentChanged(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                WordCount = value.Split(new char[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Length;
                ChapterProgress = Math.Min(WordCount, ChapterTarget);
            }
        }
    }


}
